# -*- coding: utf-8 -*-

# pip3 install python-jose[cryptography]
# pip3 install passlib[bcrypt]

from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import Union
from passlib.context import CryptContext
from pydantic import BaseModel

# 要获取如下所示的字符串,请运行：openssl rand -hex 32
# SECRET_KEY用于JWT令牌签名的随机密钥
SECRET_KEY = '''09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7'''
# 指定 JWT 令牌签名算法的变量 ALGORITHM
ALGORITHM = "HS256"
# 设置令牌过期时间的变量,这里是30分钟
ACCESS_TOKEN_EXPIRE_MINUTES = 30

# 假数据,假如这是数据库中的用户表的全量数据
fake_users_db = {
    "johndoe": {
        "username": "johndoe",
        "full_name": "John Doe",
        "email": "johndoe@example.com",
        # 下面的hash password对应的明文密码为Abc123.
        "hashed_password": "$2b$12$oC25Sks9Kg8WU8N3ddoeNugEYYQDQU9Cph7aLvP9VL.uNykdgCQQG",
        "disabled": False,
    }
}

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class User(BaseModel):
    username: str
    email: Union[str, None] = None
    full_name: Union[str, None] = None
    disabled: Union[bool, None] = None


class UserInDB(User):
    hashed_password: str


class TokenData(BaseModel):
    username: Union[str, None] = None


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证输入的密码的hash密码与数据库中记录的hash密码是否是一样的
    :param plain_password: 用户输入的密码
    :param hashed_password: hash密码
    :return:
    """
    return pwd_context.verify(plain_password, hashed_password)


def get_user(db: dict, username: str) -> UserInDB:
    """模拟在数据库中查找用户,找到之后初始化UserInDB类并返回实例"""
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)


def authenticate_user(fake_db: dict, username: str, password: str) -> Union[bool, UserInDB]:
    """
    先验证$username用户是否在数据库中存在,存在则继续验证用户输入的明文密码与数据库中记录的hash密码是否匹配
    如果都没问题就返回<class '__main__.UserInDB'>
    :param fake_db:
    :param username:
    :param password:
    :return:
    """
    user = get_user(fake_db, username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):  # user是UserInDB类的实例,所以可以点属性
        return False
    return user


def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
    """创建带exp字段的JWT字符串"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta  # 这里是utc时间,不是东八区时间
        # print(expire)  # 2023-01-18 08:14:02.453944
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})  # datetime.datetime(2023, 1, 18, 8, 14, 02, 453944)

    # SECRET_KEY对声明集进行签名的密钥
    # jwt.encode()对声明集进行编码并返回 JWT 字符串。
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def get_current_user(token: str) -> Union[UserInDB, None]:
    """
    解密JWT,即验证JWT字符串的SIGNATURE签名并返回claims(也称PAYLOAD)的信息
    :param token:
    :return:
    """
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        # print(payload)  # {'sub': 'johndoe', 'exp': 1674033230}
        username: str = payload.get("sub")
        if username is None:
            print("username 不存在")
        token_data = TokenData(username=username)
        user = get_user(fake_users_db, username=token_data.username)
        return user
    except JWTError as e:
        print(e)  # Signature verification failed.


if __name__ == '__main__':
    # form_data是模拟Request body的参数
    form_data = {
        "username": "johndoe",
        "password": "Abc123."
    }

    # 创建token过期时间
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    print(access_token_expires)  # <class 'datetime.timedelta'> 0:30:00

    # 验证Request body传入的用户是否在数据库中存在
    # 如果存在则比对password与数据库中记录的hash password是否匹配
    # 最终,没问题则返回该用户的UserInDB类的实例对象user;有问题则返回False
    user = authenticate_user(fake_users_db, form_data.get("username"), form_data.get("password"))
    print(user)

    # 创建PAYLOAD带exp字段、sub字段的JWT字符串
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    print(access_token)  # 解码用https://jwt.io/

    # 根据JWT获取当前用户
    current_user = get_current_user(access_token)
    print(current_user)
